import random
import time

from game import zz_game
from zz import zz_log, zz_code
import uiautomation as auto
from pynput.keyboard import Key

log = zz_log.of()


# 圣殿
class Game(zz_game.Game):
    def __init__(self, window: auto.PaneControl, player_data=None):
        super().__init__(window)
        self.big_begin = None  # 变大开始时间点
        self.big_enable_end_time = None  # 变大技能冷却完的时间点
        if player_data is not None:
            self.set_player_data(player_data)

    def go(self):
        self.click_if_exist("打开菜单", Key.esc, "./game/img/menu_next.png")
        self.img_click_if_exists("点击传送阵", "./game/img/menu_next.png", "./game/img/menu_collect.png")
        self.img_click_if_exists("点击收藏", "./game/img/menu_collect.png", "./game/img/menu_play_01.png")
        self.log_msg("点击圣殿")
        self.img_click("./game/img/menu_play_01.png")
        self.click_if_exist("前往圣殿入口", Key.right, "./game/img/play_select_main.png", 3)
        self.click_if_exist("选择圣殿", Key.up, "./game/img/menu_play_01_.png")
        self.click_if_exist("选择普通难度", Key.left, "./game/img/menu_play_01_state.png", 0.1, 3)
        self.log_msg("点击开始战斗圣殿")
        self.click_key(Key.space)
        return True

    def player_h(self):
        if not self.big_expire():
            return self.player_data_curr().height_big
        return super().player_h()

    def get_name(self):
        return "圣殿"

    def play1(self):
        self.big_enable_end_time = None
        if self.is_play_hot():
            # 已出现特殊关卡，过图后，不再判断
            self.play_hot_exists = True
            self.play_hot = False
        else:
            self.reset_play_hot()
        self.play1_main()

    def play1_main(self):
        """
        闯1关
        """
        index = self.play_index
        common_action = True
        big_cancel = False  # 取消变大
        self.log_msg(f"第{index}关")
        if index == 1:
            self.click_2key(Key.right, 0.2)
            self.play_ack_key()
            common_action = False
        elif index == 2:
            if not self.player_data_curr().big_disable:
                self.log_msg("图2，变大")
                self.big_enable()
            else:
                self.log_msg("变大禁用")
        # elif index == 5:
        elif index == 6:
            self.log_msg("boss图，冲到中间")
            big_cancel = True
            self.click_2key(Key.right, 0.5)
            self.play_ack_key()
            common_action = False

        if not self.big_expire():
            if self.big_expire_seconds() > 20:
                self.log_msg("变大效果剩余5秒")
                big_cancel = True
            if self.is_play_hot() and not self.big_expire():
                big_cancel = True

        if big_cancel:
            self.big_enable(False)

        if common_action:
            self.play_ack()

    def play_ack(self):
        if self.get_mini_map_data_step()[-1]['key'] == 'right':
            self.log_msg("从左边进入，直接攻击")
            if self.is_play_hot():
                self.move_center_left()
            else:
                self.click_2key(Key.right, 0.4)
        elif self.get_mini_map_data_step()[-1]['key'] == 'down':
            self.log_msg("从下方进入，需要先往左边移动")
            self.click_2key(Key.left, 0.2)
            self.click_2key(Key.down, 0.2)
            self.move_center_left()
        else:
            self.log_msg("移动到左边中间，再攻击")
            self.move_center_left()

        if not self.big_expire():
            self.log_msg("变大状态，冲2次")
            self.click_2key(Key.right, 0.5)
            self.click_2key(Key.left, 0.5)
            self.click_2key(Key.right, 0.5)

            if self.big_expire():
                self.log_msg("变大状态消失，重新再打1次")
                self.move_center_left()
                self.play_ack_key()
        else:
            self.log_msg("非变大状态，直接入技能")
            self.play_ack_key()

    def play_ack_key(self):
        """
        正常攻击方式
        """
        self.big_enable(False)
        ack_arr = self.player_data_curr().ack
        msg = ""
        for code in ack_arr:
            if isinstance(code, float):
                # 数值：暂停时间
                time.sleep(code)
                msg += f'{code}ms->'
            else:
                # 字符串：按钮
                self.click_key(code, 0.1, False)
                msg += f'{code}->'
        self.log_msg(msg[:-2])

    def big_enable(self, enable=True) -> bool:
        if enable:
            if not self.big_enable_ready():
                self.log_msg("变大技能未冷却")
                return False

            self.log_msg("变大效果开启")
            zz_game.click(Key.caps_lock)
            self.big_begin = zz_code.date_now()
            self.big_enable_end_time = zz_code.date_add_second(self.big_begin, 62)
        else:
            self.log_msg("变大效果取消")
            if not self.big_expire():
                zz_game.click(Key.caps_lock)
            self.big_begin = None
        self.clear_tmp_data()
        return True

    def big_expire(self):
        """
        变大效果是否已结束
        """
        return self.big_expire_seconds() > 25

    def big_enable_ready(self) -> bool:
        """
        变大技能是否冷却
        """
        if self.big_enable_end_time is None:
            return True
        return zz_code.date_now() > self.big_enable_end_time

    def big_expire_seconds(self) -> int:
        if self.big_begin is None:
            return 99
        return (zz_code.date_now() - self.big_begin).seconds

    def handle_main(self, buy=False):
        """
        刷图
        :param buy: true:卖装备
        """
        # 删除json文件
        # zz_game.config_clear()
        self.clear_min_map_data()
        #
        self.log_msg("等待进入战斗界面")
        if not self.img_exit("./game/img/mini_map_begin.png", 20):
            self.log_msg("进入战斗界面异常")
            return False
        self.log_msg("已进入战斗界面")

        self.play_index = 1
        while self.play_index < 7:
            self.play1()
            if self.play_index < 6:
                time.sleep(1)
                self.get_prize()
                while True:
                    next_num = self.move_next()
                    if next_num != 2:
                        break
                self.log_msg(f"next_ok: {next_num}")
                if next_num == 0:
                    # 进图失败，走错了，重新跑
                    continue

            self.set_play_index(self.play_index + 1)

        self.log_msg('等待奖品弹窗')
        self.img_exit("./game/img/play_done_alert.png", 20)
        time.sleep(1)
        prize_rnd = random.randint(1, 3)
        self.log_msg(f'出现奖品弹窗，随机选择: {prize_rnd}')
        self.click_key(f"{prize_rnd}")
        time.sleep(2)
        self.click_key(Key.esc)
        time.sleep(2)
        self.prize_buy(buy)
        self.get_prize(True)
        return True
